package com.sinosoft.jwjw.component.service.imp.system;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.sinosoft.jwjw.base.BaseCrudMapper;
import com.sinosoft.jwjw.base.BaseCrudServiceImp;
import com.sinosoft.jwjw.component.mapper.system.SUserMapper;
import com.sinosoft.jwjw.component.model.system.SMenu;
import com.sinosoft.jwjw.component.model.system.SUser;
import com.sinosoft.jwjw.component.service.system.RedisService;
import com.sinosoft.jwjw.component.service.system.SUserService;
import com.sinosoft.jwjw.utils.ConvertUtil;
import com.sinosoft.jwjw.utils.ResultDetail;
import net.sf.json.util.JSONUtils;
import org.apache.catalina.User;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Security;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 用户管理service层
 * @ver 系统自动生成代码
 */
@Service
public class SUserServiceImp extends BaseCrudServiceImp<SUser,String> implements SUserService  {

    @Autowired
    RedisService redisService;


    @Autowired
    SUserMapper sUserMapper;

    /**
     * 用户登录重置密码
     */
    @Value("${default.userResetPassword}")
    private String USER_RESET_PASSWORD = "";

    /**
     * 当前系统id
     */
    @Value("${default.systemId}")
    private String DEFAULT_SYSTEM_ID = "";


    @Override
    public BaseCrudMapper<SUser, String> getMapper() {
        return sUserMapper;
    }




    /**
     * 用户重置密码
     * @return
     * @params 必传参数 @id String
     */
    @Override
    public ResultDetail resetpwd(String id) {

        ResultDetail result = new ResultDetail();

        Map<String, Object> params = new HashMap<>();
        params.put("id",id);
        params.put("loginPwd", SecureUtil.md5(USER_RESET_PASSWORD).toLowerCase());

        int rows = getMapper().updateById(params);
        if (rows > 0) {
            result.setCode(0);
            result.setMsg("重置密码成功！");
            result.setInnermsg("");
            result.setResult(null);
        } else {
            result.setCode(500);
            result.setMsg("保存失败！");
            result.setInnermsg("");
            result.setResult(null);
        }
        return result;
    }

    /**
     * 设置用户有效无效
     * @return
     * @params 必传参数 @id String
     *          @isState String
     */
    public ResultDetail setIsState(String id , String isState) {

        ResultDetail result = new ResultDetail();

        Map<String, Object> params = new HashMap<>();
        params.put("id",id);
        params.put("isState", isState);

        int rows = getMapper().updateById(params);
        if (rows > 0) {
            result.setCode(0);
            result.setMsg("设置成功！");
            result.setInnermsg("");
            result.setResult(null);
        } else {
            result.setCode(500);
            result.setMsg("保存失败！");
            result.setInnermsg("");
            result.setResult(null);
        }
        return result;
    }


    /**
     * 登录
     * @param loginName
     * @param loginPassword md5
     * @return
     */
    public ResultDetail checkLogin(String loginName , String loginPassword) {

        ResultDetail result = new ResultDetail();

        SUser sUser = sUserMapper.selectByLoginName(loginName);
        if (sUser == null) {
            result.setCode(600);
            result.setMsg("用户不存在！");
            return result;
        } else {
            String loginPwd = sUser.getLoginPwd();
            if(loginPassword.equals(loginPwd)){

                //密码验证完成后，不显示密码
                sUser.setLoginPwd("");

                result.setCode(0);
                result.setMsg("用户验证通过！");
                result.setResult(ConvertUtil.toJSONObject(sUser));
                return result;
            }
            else{
                //是否添加当天错误登录次数
                result.setCode(601);
                result.setMsg("密码错误！");
                return result;
            }

        }
    }


    /**
     * 获取缓存用户信息
     * @return  正常返回SUser对象。若返回null，则
     */
    public SUser getCacheUser(HttpServletRequest request) {

        HttpSession session = request.getSession();
        String userId = ConvertUtil.toString(session.getAttribute("userId"));
        if("".equals(userId)){
            return null;
        }

        String strUser = redisService.getSUser(userId);
        if("".equals(strUser)){
            return null;
        }

        SUser sUser = ConvertUtil.toObject(strUser , SUser.class);
        return sUser;
    }

    /**
     * 获取缓存用户菜单信息
     * @param request
     * @return
     */
    public List<SMenu> getCacheUserMenu(HttpServletRequest request) {

        HttpSession session = request.getSession();
        String systemId = ConvertUtil.toString(session.getAttribute("systemId"));
        if("".equals(systemId)){
            return null;
        }
        String userId = ConvertUtil.toString(session.getAttribute("userId"));
        if("".equals(userId)){
            return null;
        }

        String strSystemMenu = redisService.getSUserSystemMenu(userId , systemId);
        List<SMenu> list = null;
        if(strSystemMenu == null || "".equals(strSystemMenu)){
            list = ConvertUtil.toListObject(strSystemMenu , SMenu.class);
        }
        return list;
    }

    /**
     * 操作时刷新缓存信息
     * @param request
     * @return
     */
    public boolean refreshCache(HttpServletRequest request) {

        //刷新session 默认2小时
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(2 * 3600);//以秒为单位

        String systemId = ConvertUtil.toString(session.getAttribute("systemId"));
        if("".equals(systemId)){
            return false;
        }
        String userId = ConvertUtil.toString(session.getAttribute("userId"));
        if("".equals(userId)){
            return false;
        }

        //刷新redis 默认2小时
        redisService.refreshUser(userId , systemId);

        return true;
    }

}
